/**
 *  serviceEvaluation.html 页面的javascript文件
 */

$().ready(function () {

    // ---------判断用户信息是否失效---------
    isUserInfoNull();

    // -----------------变量定义---------------------------
    var vehicleDeliveryId = getUrlParam().vehicleDeliveryId; // 车辆派送id
    var isEvaluation; // 是否评价
    var operationFlag = true; // 评价是否可以操作标志
    var $evaluationMessage = $("#evaluation-message"); // 服务评价内容
    var evaluationMessage;
    var driverId;
    var mapDriver = {};
    // ----------服务评价----------
    var serviceStatus = 0;
    var driverSkill = 0;
    var overallFeel = 0;
    // ----------司机列表滑动部分变量定义---------
    var driverSize = 2;
    var loopVal = 0; // 循环变量的值

    // 星星的class
    var starClassCount;
    var starClassCount2;
    var starClassCount3;

    // ----------根据vehicleDeliveryId获取车辆派送信息中的司机列表----------
    $.get("/bcs/manage/getBaseInfoByVehicleDeliveryId?vehicleDeliveryId=" + vehicleDeliveryId,
        function (result) {
            if (result.manageResult.errcode === 0){
                console.log("获取成功");

                var targetData = result.manageResult.data;
                driverSize = targetData.driverInfoVoList.length;
                // 将司机信息渲染到页面
                var htmlDriverImg = '';
                for (var i=0; i<targetData.driverInfoVoList.length; i++){
                    htmlDriverImg += '<div class="weui-flex__item" >';
                    if (i === 0){
                        htmlDriverImg += '<div class="placeholder driver-img selected-driver-img" style="text-align: center;" id="'+ targetData.driverInfoVoList[i].id +'">';
                        htmlDriverImg += '<img src="'+targetData.driverInfoVoList[i].driverImg+'" style="width: 30px; margin-top: 5px">';
                        htmlDriverImg += '<div class="placeholder selected-driver-name" style="text-align: center; margin-bottom: 5px" id="'+targetData.driverInfoVoList[i].id+'-img" >';
                        htmlDriverImg += '<span>'+targetData.driverInfoVoList[i].driverName +'</span></div></div></div>';
                    } else {
                        htmlDriverImg += '<div class="placeholder driver-img" style="text-align: center;" id="'+ targetData.driverInfoVoList[i].id +'">';
                        htmlDriverImg += '<img src="'+targetData.driverInfoVoList[i].driverImg+'" style="width: 30px; margin-top: 5px">';
                        htmlDriverImg += '<div class="placeholder" style="text-align: center; margin-bottom: 5px" id="'+targetData.driverInfoVoList[i].id+'-img" >';
                        htmlDriverImg += '<span>'+targetData.driverInfoVoList[i].driverName +'</span></div></div></div>';
                    }
                }
                $("#flex-driver-img").html(htmlDriverImg);

            } else {
                console.log("获取失败")
            }
        });

    // ----------提交评价----------
    $("#save").on("click", function () {

        if (serviceStatus === 0 && driverSkill === 0 && overallFeel === 0){
            $("#dialog .weui-dialog__title").text("需要对本次服务做出评价哦");
            $("#dialog").show();
        } else {
            // 评价内容为空判断
            if ($evaluationMessage.val() === "" || $evaluationMessage.val() === undefined || $evaluationMessage.val() === null){
                evaluationMessage = "空"
            } else {
                evaluationMessage = $evaluationMessage.val();
            }
            // 服务评价信息的发送
            $("#loadingToast .weui-toast__content").text("评价中");
            $("#loadingToast").fadeIn(100);
            $.post("/bcs/user/serviceEvaluation", {
                "vehicleDeliveryId" : vehicleDeliveryId,
                "serviceAttitude" : serviceStatus,
                "driverSkill" : driverSkill,
                "overallFeel" : overallFeel,
                "evaluationMessage" : evaluationMessage,
                "driverId" : driverId
            }, function (result) {
                if (result.bookResult.errcode === 0){
                    $("#loadingToast").hide();
                    $("#toast .weui-toast__content").text("评价成功");
                    $("#toast").fadeIn(100);
                    setTimeout(function(){
                        $("#toast").fadeOut(100);
                    }, 2000);
                    // 跳往首页
                    window.location.href = '../index.html?vehicleDeliveryId=' + vehicleDeliveryId;
                }
            })
        }

    });

    $("#iknow").on("click", function () {
        $("#dialog").show();
    });

    // ----------点击选择对象----------
    $("#flex-driver-img").on("click",".driver-img",function () {
        console.log($(this));
        console.log($(this).context.id);
        driverId = $(this).context.id;
        // 先移除所有"my-color"属性
        $("#flex-driver-img .weui-flex__item").each(function () {
            console.log("我要移除了");
            $("#flex-driver-img .weui-flex__item").children(".placeholder").removeClass("selected-driver-img")
            $("#flex-driver-img .weui-flex__item").children(".placeholder").children(".placeholder").removeClass("selected-driver-name");
        });
        // 再给点击的div添加"my-color"属性
        $(this).addClass("selected-driver-img");
        $(this).children(".placeholder").addClass("selected-driver-name");
        initPageInfo(vehicleDeliveryId, driverId);
    });

    // ----------默认选定的对象----------
    setTimeout(function(){
        // 默认被选定的对象
        var defaultId = $(".selected-driver-img").attr("id");
        console.log("默认被选定对象id = " + defaultId);
        // 后台获取评价结果
        initPageInfo(vehicleDeliveryId, defaultId);
    }, 100);

    // ----------左滑右滑事件----------
    $("#driver-list").swipe({

        swipe : function (event, direction, distance, duration, fingerCount) {

            if(direction === "left"){
                loopVal -= 1;
                console.log("zuozuozuo---------("+loopVal+")");
                loopSelect(loopVal);

            } else if(direction === "right"){
                loopVal += 1;
                console.log("youyouyou---------"+loopVal);
                loopSelect(loopVal);

            }
        }
    });

    // ----------循环选择司机----------
    function loopSelect(loopIndex) {
        $("#flex-driver-img .weui-flex__item").each(function (ii) {
            $(this).children(".placeholder").removeClass("selected-driver-img");
            $(this).children(".placeholder").children(".placeholder").removeClass("selected-driver-name");
            if (loopVal >= 0){
                if (ii ===  loopVal % driverSize){
                    addClassAndSearchEvaluationResult($(this));
                }
            } else {
                if (ii === Math.abs(Math.floor(loopVal/driverSize)*driverSize)+loopVal){
                    addClassAndSearchEvaluationResult($(this));
                }
            }

        });
    }

    // ----------添加选定效果和查询该用户已评价过该司机------------
    function addClassAndSearchEvaluationResult($this) {
        /**
         * 必须接受$(this)，否则获取的值为undefine
         */
        // 高亮显示被选中的对象
        $this.children(".placeholder").addClass("selected-driver-img");
        $this.children(".placeholder").children(".placeholder").addClass("selected-driver-name");
        var selectedId = $(".selected-driver-img").attr("id");
        console.log("被选定对象id = " + selectedId);
        // 后台获取评价结果
        initPageInfo(vehicleDeliveryId, selectedId);
    }

    // ----------星级效果实现----------
    function starEvaluation(flag) {
        console.log(flag);
        if (flag){
            // ----------星级效果实现----------
            var p = document.getElementById('star'), stars = p.children, inner = stars[0];
            var p2 = document.getElementById('star2'), stars2 = p2.children, inner2 = stars2[0];
            var p3 = document.getElementById('star3'), stars3 = p3.children, inner3 = stars3[0];

            for (var i = 1; i < stars.length; i++) {
                stars[i].onmouseover = function () {
                    inner.style.width = 20 * $(this).attr('title') + '%';
                    // show.innerHTML = this.title;
                };
                stars[i].onclick = function () {
                    p.className = 'star star-' + $(this).attr('title');
                    console.log('11111    ' + $(this).attr('title'));

                    serviceStatus = this.title;
                    console.log(serviceStatus);
                }
            }
            for (var j = 1; j < stars2.length; j++) {
                stars2[j].onmouseover = function () {
                    inner2.style.width = 20 * $(this).attr('title') + '%';
                    // show2.innerHTML = this.title;
                };
                stars2[j].onclick = function () {
                    p2.className = 'star star-' + $(this).attr('title');
                    console.log('22222    ' + $(this).attr('title'));

                    driverSkill = this.title;
                    console.log(driverSkill);
                }
            }
            for (var k = 1; k < stars3.length; k++) {
                stars3[k].onmouseover = function () {
                    inner3.style.width = 20 * $(this).attr('title') + '%';
                    // show3.innerHTML = this.title;
                };
                stars3[k].onclick = function () {
                    p3.className = 'star star-' + $(this).attr('title');
                    console.log('33333    ' + $(this).attr('title'));
                    overallFeel = this.title;
                    console.log(overallFeel);
                }
            }
            p.onmouseout = function () {
                if (this.className.indexOf('star-') === -1) {
                    inner.style.width = '0';
                    // show.innerHTML = '';
                } else {
                    inner.style.width = null;
                    // show.innerHTML = show.title;
                }
            };

            p2.onmouseout = function () {
                if (this.className.indexOf('star-') === -1) {
                    inner2.style.width = '0';
                    // show2.innerHTML = '';
                } else {
                    inner2.style.width = null;
                    // show2.innerHTML = show2.title;
                }
            };

            p3.onmouseout = function () {
                if (this.className.indexOf('star-') === -1) {
                    inner3.style.width = '0';
                    // show3.innerHTML = '';
                } else {
                    inner3.style.width = null;
                    // show3.innerHTML = show3.title;
                }
            };
            // ----------星级效果实现结束----------
        }
    }

    // ----------获取评价并渲染到页面----------
    function getEvaluationInfo(vehicleDeliveryId, driverId) {
        $.get("/bcs/user/getServiceEvaluationInfo?vehicleDeliveryId=" + vehicleDeliveryId + "&driverId=" + driverId, function (result) {

            console.log(result);
            if (result.bookResult.errcode === 0){
                var targetData = result.bookResult.data;
                // 回显评价结果
                $("#star").addClass("star-"+targetData.d_service_attitude);
                $("#star2").addClass("star-"+targetData.d_driving_skill);
                $("#star3").addClass("star-"+targetData.d_overall_feel);
            }

        });
    }

    // -----------获取用户信息-----------
    function initPageInfo(vehicleDeliveryId, driverId) {
        $.get("/bcs/user/getServiceEvaluationInfo?vehicleDeliveryId=" + vehicleDeliveryId + "&driverId=" + driverId,
            function (result) {
                console.log(result);
                // 清空页面素据
                $("#star").removeClass("star-"+starClassCount);
                $("#star2").removeClass("star-"+starClassCount2);
                $("#star3").removeClass("star-"+starClassCount3);
                $evaluationMessage.val("");
                if (result.bookResult.errcode === 0){
                    var targetData = result.bookResult.data;
                    // 表示已评价
                    console.log("已评价");
                    // 隐藏“提交”按钮
                    $("#one").hide();
                    operationFlag = false;
                    // 禁止输入
                    $evaluationMessage.prop("disabled","disabled");

                    // 渲染评论
                    $evaluationMessage.val(targetData.evaluation_message);
                    // 获取评价并渲染到页面-
                    $("#star").addClass("star-"+targetData.d_service_attitude);
                    $("#star2").addClass("star-"+targetData.d_driving_skill);
                    $("#star3").addClass("star-"+targetData.d_overall_feel);
                    starClassCount = targetData.d_service_attitude;
                    starClassCount2 = targetData.d_driving_skill;
                    starClassCount3 = targetData.d_overall_feel;
                    starEvaluation(operationFlag);

                }else {
                    // 表示没有评价
                    console.log("没有评价");
                    // 显示“提交”按钮
                    $("#one").show();
                    operationFlag = true;
                    starEvaluation(operationFlag);
                }
        });
    }

    // ----------判断用户是否失效---------
    function isUserInfoNull() {
        $.get("/bcs/user/isUserInfoNull", function (result) {

            if (result.bookResult.errcode === 1){
                // 用户信息已失效, 直接跳转
                $("#loadingToast .weui-toast__content").text("登录已过期,正在登录中");
                $("#loadingToast").fadeIn(100);
                // 使用微信oauth 的回调链接方式，进行再次登录
                window.location.href = result.bookResult.data;
            }
        });
    }

    // -----------获取url中的参数-----------
    function getUrlParam() {
        var url = window.location.href;
        console.log(url);
        if(url.indexOf("?") === -1) return;
        var urlSplit = url.split("?")[1];
        var res = [];
        if(urlSplit.indexOf("&") === -1) {
            var arr1 = urlSplit.split("=");
            res[arr1[0]] = arr1[1]
        } else {
            var arr2 = urlSplit.split("&");
            for(var i = 0; i < arr2.length; i++) {
                var key = arr2[i].split("=");
                res[key[0]] = key[1]
            }
        }
        return res
    }

});